package com.yunduansing.demo.web.system;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import com.yunduansing.demo.exception.FileEmptyException;
import com.yunduansing.demo.model.common.ResponseModel;
import com.yunduansing.demo.web.BaseController;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "文件操作")
@RestController
public class FileController extends BaseController {
    @Value("${file.upload}")
    private String baseUploadPath;

    @PostMapping("/file/upload")
    @ApiOperation("上传")
    @ApiParam(value = "文件，key为file",example = "formData.append('file');")
    public ResponseModel<String> upload(@RequestParam("file") MultipartFile file) throws FileEmptyException {
        if(file.isEmpty()) throw new FileEmptyException("上传文件不能空！");
        String fileName=file.getOriginalFilename();//得到文件名
        String suffixName=fileName.substring(fileName.lastIndexOf("."));//得到后缀名
        String filepath=baseUploadPath+"/user/images/";//指定图片上传到哪个文件夹的路径
        File dir=new File(filepath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        fileName= UUID.randomUUID()+suffixName;//重新命名图片，变成随机的名字
        File dest=new File(filepath+fileName);//在上传的文件夹处创建文件
        try {
            file.transferTo(dest);//把上传的图片写入磁盘中
            return ok("/file/user/images/"+fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return convertToResponseModel(false, "上传失败。");
        }
    }
}